import request from '@/utils/http'
import {useUserStore} from '@/store/modules/user'
import { CustomAxiosRequestConfig } from './http'
import { BaseResult } from '@/types/axios'

let promise = null;

export async function refreshToken() {
  const userStore = useUserStore()

  if(promise) {
    return promise
  }
  promise = new Promise(async resolve => {
    const res = await request.get<BaseResult>({
      url:'/user/auth/refresh_token',
      params:{
        refresh_token:userStore.refreshToken
      },
      _isRefreshToken:true
    })
    console.log('刷新是否成功',res)
    resolve(res.code === 0)
    userStore.setToken(res.data.access_token,res.data.refresh_token)
  })
  promise.finally(() => {
    promise = null
  })
  return promise
}

export function isRefreshToken(config: CustomAxiosRequestConfig) {
  return !!config._isRefreshToken
}
